<?php

namespace Admin\Controller;

use Org\Util\String;
use Think\Controller;

class BookController extends ComController {

    public function add_book() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        if ($admin['level'] > 0) {
            $this->error('权限不足，无法访问');
        }
        $t = M('type');
        $type = $t->select();
        $this->assign('type', $type);
        $this->display();
    }

    public function edit_book() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
//        if ($admin['level'] > 0) {
//            $this->error('权限不足，无法访问');
//        }
        $t = M('type');
        $type = $t->select();
        $this->assign('type', $type);
        $b = M('book');
        $book = $b->where(array('id' => $_GET['id']))->find();
        $this->assign('book', $book);
        $this->display();
    }

    public function edit_book_chanrge() {
        $id = $_POST['id'];
        $bi = M('bookinfo');
        $gold = $_POST['gold'];
        $biid = $_POST['arr_biid'];
        $bi->where(['bid' => $id, 'id' => ['in', $biid]])->setField('gold', $gold);
        $this->success('批量修改收费成功');
    }

    public function edit_book_chanrge2() {
        $id = $_POST['id'];
        $bi = M('bookinfo');
        $gold = $_POST['gold'];
        $bi->where(['bid' => $id])->setField('gold', $gold);
        $this->success('批量修改收费成功');
    }

    public function do_add_book() {
        $data = $_POST['data'];
        if (empty($data['tid']) || empty($data['title'])) {
            $this->error('内容提交不能为空');
        }
        M()->startTrans();
        $t = M('type');
        $type = $t->where(array('id' => $data['tid']))->find();
        $w['name'] = $type['name'];
        $w['tid'] = $data['tid'];
        $w['title'] = $data['title'];
        $w['img'] = $data['img'];
        $w['content'] = $data['content'];
        $w['sex'] = $data['sex'];
        $w['state'] = $data['state'];
        $w['source'] = $data['source'];
        $w['num'] = $data['num'];
        $w['closed'] = 1; //新加的收是下架状态的
        $b = M('book');
        $i = $b->add($w);
        if (!empty($data['url'])) {//表示通过采集来的内容
            if (checkDomain($data['url'])) {
                //表示采集网上内容
            } else {
                $Bookinfo = M('Bookinfo','n_','DB_CONFIG_DEV');     
                $bid = $data['url'];
                $bookinfo = $Bookinfo->field('title2,content,number')->where(['bid' => $bid])->order('number asc')->select();
                foreach ($bookinfo as $key => $value) {
                    $bookinfo[$key]['bid'] = $i;
                    $bookinfo[$key]['time'] = time();
                }
                $ii = D('Bookinfo')->addAll($bookinfo);
            }
            $tr = M('transfer','n_','DB_CONFIG_DEV');
            $tw['bid'] = $data['url'];
            $tw['trtime'] = time();
            $tf = $tr->add($tw);
        }
        if (!empty($i) && !empty($ii) && !empty($tf)) {
            M()->commit();
            $this->success('添加书籍成功');
        } else {
            M()->rollback();
            $this->error('添加书籍失败，请重试');
        }
    }

    public function do_edit_book() {
        if (empty($_POST['tid']) || empty($_POST['title'])) {
            $this->error('内容提交不能为空');
        }
      
      	$upload = new \Think\Upload();
        $upload->maxSize = 8388608;
        $upload->exts = array('jpg', 'png', 'jpeg', 'txt');
        $upload->rootPath = "./Public/Uploads/book/";
        $upload->savePath = '';
        $upload->autoSub = false;
        $upload->saveName = array('uniqid', '');
        $info = $upload->upload();
        if(!empty($info)){
            $w['img'] = 'http://'.$_SERVER['HTTP_HOST']."/Public/Uploads/book/".$info['img']['savename'];
        }
        $id = $_POST['id'];
        $t = M('type');
        $post = I('post.');
        $w['tid'] = $post['tid'];
        $w['title'] = $post['title'];
        //$w['img'] = $post['img'];
        $w['content'] = $post['content'];
        $w['sex'] = $post['sex'];
        $w['num'] = $post['num'];
        $w['vip'] = $post['vip'];
        $w['state'] = $post['state'];
        $w['hidden'] = $post['hidden'];

        $w['free_chapter'] = $post['free_chapter'] ? $post['free_chapter'] : 0;

        if (!empty($post['author'])) {
            $w['author'] = $post['author'];
        }
        if (!empty($post['free_days'])) {
            $w['free_days'] = $post['free_days'];
        }
        if (!empty($post['orderby'])) {
            $w['orderby'] = $post['orderby'];
        }
        $w['free_time'] = $post['free_time'];
        if (empty($post['free_time'])) {//书本免费，避免误操作，把其他数据清零
            $w['free_days'] = 0;
            $w['vip'] = 0;
        }
        if(!empty($_POST['username']) && !empty($_POST['password'])){
            D('author')->add([
                'username' => $_POST['username'],
                'password' => md5($_POST['password']),
                'bid' => $id,
            ]);
        }
        $b = M('book');
        $i = $b->where(array('id' => $id))->save($w);
        if ($i > 0 || $id) {
            if (!empty($post['free_days'])) {
                $redis = redis(); //redis运用
                $redis->sADD('freedays', $_POST['id']);
            }
            $this->success('编辑书籍成功');
        } else {
            $this->error('编辑书籍失败，请重试');
        }
    }

    public function add_book_type() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        if ($admin['level'] > 0) {
            $this->error('权限不足，无法访问');
        }
        $w = [];
        if (!empty($_GET['id'])) {
            $w['id'] = $_GET['id'];
            $t = M('type');
            $type = $t->where($w)->find();
            $this->assign('type', $type);
        }


        $this->display();
    }

    //购买一本书
    function buyBook(){
        if (empty($_POST['bid'])) {
            $this->error('bid不可为空');
        }
        if (empty($_POST['book_name'])) {
            $this->error('书名不能为空');
        }
        if (empty($_POST['user_id'])) {
            $this->error('购买用户id不能为空');
        }
        $bid = $_POST['bid'];
        $book_name = $_POST['book_name'];
        $user_id = $_POST['user_id'];
        $bookshelves = D('bookshelves');
        $result = $bookshelves->where(['b_id'=>$bid,'user_id'=>$user_id])->find();
        if(!$result){
            $id = $bookshelves->add(['b_id'=>$bid,'user_id'=>$user_id,'is_all_buy'=>1,'add_time'=>time()]);
            if($id){
                $this->success("添加成功");
                die();
            }
            $this->error('添加失败');
        }
        $this->success("此书已经添加过此用户了");
    }

    public function do_add_book_type() {

        if (empty($_POST['name'])) {
            $this->error('分类名称不可为空');
        }
        if (empty($_POST['sex'])) {
            $this->error('请选择性别类型');
        }
        $upload = new \Think\Upload();
        $upload->maxSize = 8388608;
        $upload->exts = array('jpg', 'png', 'jpeg', 'txt');
        $upload->rootPath = "./Public/Uploads/book/";
        $upload->savePath = '';
        $upload->autoSub = false;
        $upload->saveName = array('uniqid', '');
        $info = $upload->upload();


        $t = M('type');
        $w['name'] = $_POST['name'];
        $w['sex'] = $_POST['sex'];
        if(!empty($info)){
            $cover= 'http://'.$_SERVER['HTTP_HOST']."/Public/Uploads/book/".$info['cover']['savename'];
            $w['cover'] = $cover;
        }
        $w['closed'] = $_POST['closed']?:0;
        if (!empty($_POST['id'])) {
            $w['id'] = $_POST['id'];
            $i = $t->save($w);
            $this->success('修改书籍分类成功');
        } else {
            $i = $t->add($w);
            $this->success('添加书籍分类成功');
        }
    }

    public function book_type() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        $type = D('Type')->select();
        $this->assign('type', $type);
        $this->display();
    }

    public function add_book_info_author() {
        if(empty($_SESSION['author_id'])){
            $this->error('登入超时',U('Admin/Login/author_login'));
        }
        $author_id = $_SESSION['author_id'];
        $author = D('Author')->find($author_id);
        $params['id'] = $author['bid'];
        if (!empty($params['id'])) {
            $book = D('Book')
                ->table('__BOOK__ AS b')
//            ->join('__TYPE__ AS t on b.tid = t.id')
                ->where("b.id = {$params['id']}")
                ->find();
            $this->assign('book', $book);
        } else {
            $this->error('当前帐号下没有可编辑的书籍');
        }
//        $t = M('type');
//        $type = $t->select();
//        $this->assign('type', $type);
        $this->display();
    }

    public function add_book_info() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $params = $this->params();
        if (!empty($params['id'])) {
            $book = D('Book')
            ->table('__BOOK__ AS b')
//            ->join('__TYPE__ AS t on b.tid = t.id')
            ->where("b.id = {$params['id']}")
            ->find();
            $this->assign('book', $book);
        } else {
            $this->error('请先选择书籍', U('book_list'));
        }
        $this->assign('admin', $admin);
        if ($admin['level'] > 0) {
            $this->error('权限不足，无法访问');
        }
        $t = M('type');
        $type = $t->select();
        $this->assign('type', $type);
        $this->display();
    }



    public function edit_bookinfo() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
//        if ($admin['level'] > 0) {
//            $this->error('权限不足，无法使用此功能');
//        }
        $bi = M('bookinfo');
        $bookinfo = $bi->join('n_book ON n_book.id = n_bookinfo.bid', 'LEFT')->where(array('n_bookinfo.id' => $_GET['id']))->field('n_book.name,n_book.title,n_bookinfo.*')->find();
        $this->assign('bookinfo', $bookinfo);
        $this->display();
    }

    public function changebook() {
        $b = M('book');
        $book = $b->where(array('closed' => 1, 'tid' => $_GET['tid']))->select();
        if (!$book) {
            $book = 'error';
        }
        $this->ajaxReturn($book);
    }

    public function do_add_book_info() {
        $params = $this->params();
        foreach ($params as $key => $value) {
            if (empty($value)) {
                $this->error('所有数据不能为空');
            }
        }
        $number = trim($params['next_chapter_number']);
        $bi = M('bookinfo');
        $last = $bi->where(['bid' => $params['bid']])->order('number desc')->find();
        if($number>$last['number']){
            $result = true;
        }else{
            $result = $bi->where(['bid' => $params['bid'], 'number' => ['egt', $number]])->setInc('number');
        }
        
        if ($result) {
            $data = [
                'bid' => $params['bid'],
                'title2' => $params['title2'],
                'content' => stpstr($params['content']),
                'time' => time(),
                'number' => $number
            ];
            $i = $bi->add($data);
            if($i){
                $sql = "SET @num = 0;UPDATE n_bookinfo SET number = (@num := @num + 1) WHERE bid = {$params['bid']}";
                $result = D('Bookinfo')->comment('修正章节序号')->execute($sql);
                $this->success('添加章节成功');
                die();
            }
            $this->success('添加失败，请重试');
        }

    }

    public function do_edit_bookinfo() {
        $params = $this->params();
        foreach ($params as $key => $value) {
            if (empty($value)) {
                $this->error('所有数据不能为空');
            }
        }
        $bi = M('bookinfo');
        $w['title2'] = $params['title2'];
        $w['content'] = stpstr($params['content']);
        $w['number'] = $params['number'];
        $i = $bi->where(array('id' => $params['id']))->save($w);
        if ($i > 0) {
            $this->success('编辑书籍章节成功');
        } else {
            $this->error('编辑书籍章节失败，请重试');
        }
    }

    public function book_list() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        $page = I('get.page', 1);
        $pre_page = I('get.pre_page', 30);
        $b = M('book');
        if (!empty($_GET['sex'])) {
            $w['sex'] = $_GET['sex'];
        }
        if (!empty($_GET['keyword'])) {
            $keyword = trim($_GET['keyword']);
            $w['title|n_book.id'] = ['like', "%" . $keyword . "%"];
        }
        if (!empty($_GET['state'])) {
            $w['state'] = $_GET['state'];
        }
        if (!empty($_GET['tid'])) {
            $w['tid'] = $_GET['tid'];
        }
        $w['free_time'] = $_GET['free_time'] == 1 ? 1 : 0;

        $w['closed'] = 0;
        if(isset($_GET['closed'])){
            $w['closed'] = $_GET['closed'];
        }

        $t = M('type');
        $type = $t->order("id asc")->select();
        $w['del_time'] = 0;
        $count = $b->where($w)->count();
        $Page = new \Think\Page($count, $pre_page);
        $show = $Page->show();
        $books = $b->where($w)->limit($Page->firstRow . ',' . $Page->listRows)->join('n_transfer ON n_transfer.bid = n_book.id', 'LEFT')->field('n_transfer.bid,n_transfer.trtime,n_book.*')->order('is_top desc')->select();
        $this->assign('type', $type);
        $this->assign('closed', $w['closed']);
        $this->assign('keyword', $_GET['keyword']);
        $this->assign('books', $books);
        $this->assign('page', $show);
        $this->display();
    }

    public function book_doshow() {
        $b = M('book');
        $book = $b->where(array('id' => $_GET['id']))->find();
        if ($book['show'] == '1') {
            $w['show'] = 2;
        } else {
            $w['show'] = 1;
        }
        $i = $b->where(array('id' => $_GET['id']))->save($w);
        if ($i > 0) {
            $this->success('修改推荐状态成功');
        } else {
            $this->error('修改推荐状态失败，请重试');
        }
    }

    public function book_doeic() {
        $b = M('book');
        $book = $b->where(array('id' => $_GET['id']))->find();
        if ($book['eic'] == '1') {
            $w['eic'] = 2;
        } else {
            $w['eic'] = 1;
        }
        $i = $b->where(array('id' => $_GET['id']))->save($w);
        if ($i > 0) {
            $this->success('修改编辑推荐状态成功');
        } else {
            $this->error('修改编辑推荐状态失败，请重试');
        }
    }

    public function is_top_book() {
        $b = M('book');
        $get = I('get.');
        if ($b->save($get)) {
            $this->success('修改编辑推荐状态成功');
        }
    }

    public function closed_book() {
        $b = M('book');
        $get = I('get.');
        if ($b->save($get)) {
            $this->success('修改编辑推荐状态成功');
        }
    }

    public function book_dohot() {
        $b = M('book');
        $book = $b->where(array('id' => $_GET['id']))->find();
        if ($book['hot'] == '1') {
            $w['hot'] = 2;
        } else {
            $w['hot'] = 1;
        }
        $i = $b->where(array('id' => $_GET['id']))->save($w);
        if ($i > 0) {
            $this->success('修改编辑推荐状态成功');
        } else {
            $this->error('修改编辑推荐状态失败，请重试');
        }
    }

    public function book_share() {
        $this->checklogin();
        $sequence = 'number asc';
        $ad = M('admin');
        $admin = $ad->where(array('id' => $_SESSION['aid']))->find();
        $this->assign('admin', $admin);
        $page = I('get.page', 1);
        $pre_page = I('get.pre_page', 100);
        $b = M('book');
        $bi = M('bookinfo');
        $w = array('bid' => $_GET['bid']);
        if (!empty($_GET['titlekeyword'])) {
            $w['number|title2'] =['like',"%".$_GET['titlekeyword']."%"];
        }
        if (!empty($_GET['sequence'])) {
            $sequence = 'number '.$_GET['sequence'];
        }
        $count = $bi->where($w)->count();
        $Page = new \Think\Page($count, $pre_page);
        $show = $Page->show();
        $book = $b->where(array('id' => $_GET['bid']))->find();
        $bookinfo = $bi->where($w)->order($sequence)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('book', $book);
        $this->assign('titlekeyword', $_GET['titlekeyword']);
        $this->assign('bookinfo', $bookinfo);
        $this->assign('page', $show);
        $this->display();
    }
    
    public function creatlinks() {
        //落地页域名
        if (empty(I('get.'))) {
            $this->ajaxReturn(false);
        }
        $data = I('get.');
        $wechat = D('Wechat')->find(1);
        $serurl = $wechat['serurl']; //跳转域名
        $jsurl = $wechat['jsurl']; //调用分享接口域名
        $pre_domin = md5(uniqid());
        $openurl = 'http://' . $pre_domin . '.' . $serurl . '/';
        $articleurl = 'http://' . $jsurl . "/Home/book/helloworld?id={$data['id']}";
        if(!empty($data['type'])){
            $articleurl = 'http://' . $jsurl . "/Home/book/helloworld/type/1/id/".$data['id'];
        }
        $durl = $openurl . 'home/book/share?url=' . urlencode($articleurl);
        $this->ajaxReturn($durl);
    }

    public function book_article() {
        $this->checklogin();
        $bi = M('bookinfo');
        $bookinfo = $bi->where(array('id' => $_GET['id']))->find();
        $number = $bookinfo['number'] + 1;
        $w['number'] = array('lt', $number);
        $w['bid'] = $bookinfo['bid'];
        $bookinfos = $bi->where($w)->select();
        foreach($bookinfos as &$v){
            $v['content']  = str_replace("&nbsp;&nbsp;&nbsp;&nbsp;", "<p/>", $v['content']);
        }
        $this->assign('bookinfos', $bookinfos);
        $nextbi = $bi->where(array('bid' => $bookinfo['bid'], 'number' => $number))->find();
        if (!$nextbi) {
            $this->error('下一章节不存在，无法生成文案');
        }
        $article = [];
        $article = D('article')->where(['bid'=>$bookinfo['bid']])->find();
        if(!empty($article)){
            $this->assign('article', $article);
        }
//        $this->assign('url', $url);
//        $this->assign('durl', $durl);
        $sign = String::keyGen();
        $this->assign('sign',$sign);
        $this->assign('pre_url',c('pre_url'));
        $this->assign('id', $_GET['id']);
        $this->display("book_article_4");
    }
    
    public function add_book_txt() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        if ($admin['level'] > 0) {
            $this->error('权限不足，无法访问');
        }
        $t = M('type');
        $type = $t->select();
        $this->assign('type', $type);
        $this->display();
    }

    public function do_add_book_txt() {
      	ini_set('memory_limit','500M');
        if (empty($_POST['tid']) || empty($_POST['title'])) {
            $this->error('内容提交不能为空');
        }
        
        
        //$w['img'] = 'http://'.$_SERVER['HTTP_HOST']."/Public/Uploads/book/".$info['img']['savename'];
        $t = M('type');
        $type = $t->where(array('id' => $_POST['tid']))->find();
        $w['name'] = $type['name'];
        $w['tid'] = $_POST['tid'];
        $w['title'] = $_POST['title'];
        $w['author'] = $_POST['author'];
        //$w['img'] = 'http://'.$_SERVER['HTTP_HOST']."/Public/Uploads/book/".$info['img']['savename'];
      	$w['img'] = '1';
        $w['content'] = $_POST['content'];
        $w['sex'] = $_POST['sex'];
        $w['state'] = $_POST['state'];
        $w['closed'] = 1;
      	$Model = M();
		$Model->startTrans();
        $b = M('book');
        $b_id = $b->add($w);
      	$upload = new \Think\Upload();
        $upload->maxSize = 52428800;//23753678   23412399

        $upload->exts = array('jpg', 'png', 'jpeg', 'txt','zip');
        $upload->rootPath = "./Public/Uploads/book/";
        $upload->savePath = '';
        $upload->autoSub = false;
        $upload->saveName = array('uniqid', '');
        $info = $upload->upload();
        if(!$info) {// 上传错误提示错误信息
           $this->error($upload->getError().'大小不能超过50M');
            die();
        }
		$txt = $info['txt']['savename'];
      	if(empty($txt)){
        	$Model->commit();
            $this->success('添加书籍成功1');
            die();
        }
        $file_path = "Public/Uploads/book/" . $txt;
        if ($b_id > 0) {
         if($info['ext']=='zip'){
             $zip = new \ZipArchive();
             if ($zip->open($file_path) === true) {

                 $zip->extractTo($upload->rootPath);

                 $zip->close();

                 return true;

             } else {

                 return false;

             }
         }
        $contents = file_get_contents($file_path);
        $encoding = mb_detect_encoding($contents, array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII'));
         $file = @fopen($file_path,'r');
         $content = array();
 		 $i = 0;
          while (!feof($file)){
            //$content[$i] = fgets($file);
              if ($encoding != false) {
                  //iconv ()将$encoding 转换成“UTF-8”
                  $str = iconv($encoding, 'UTF-8', fgets($file));
                  if ($str != "" and $str != NULL) {
                      $content[$i] = $str;
                  }
              }else{
                  $content[$i] = mb_convert_encoding(fgets($file),"UTF-8","Unicode");
              }

            $i++ ;
          }

          if(empty($content)){
            echo "没有内容";
            die();
          }
          fclose($file);
          $content = array_filter($content); //数组去空
        $bookinfo = array();
        $i = 0;
        $j = 0;
        $pos = strpos($content,'###');
        foreach ($content as $k => $v) {
            if(!empty($v)){
                $d = $pos?preg_match("/###/iU",$v,$a):preg_match("/第(.*)章 /iU",$v,$a);
                if(!empty($d) && !empty($a)){
                    $title2 = str_replace('###','',$v);
                    $bookinfo[$i]['title2'] = !empty($title2)?$title2:'导入空数据';
                    $bookinfo[$i]['number'] = $i+1;
                    $bookinfo[$i]['tid'] = $_POST['tid'];
                    $bookinfo[$i]['bid'] = $b_id;
                 	$bookinfo[$i]['time'] = time();
                    $j = $i;
                    $i++;
                }else{
                    if(!empty($bookinfo[$j]['title2'])){
                        $bookinfo[$j]['content'] .= !empty($v)?$v:'导入空数据';
                    }
                }
            }
          unset($content);
        }

        if(empty($bookinfo)){
            $this->success('转换格式后数据是空');
          	die();
        }
       $bi = M('bookinfo');
        //分片插入
//        $len = count($bookinfo);
//        $num = 1;
//        if($len>500){
//            $num = ceil($len/500);
//        }
//       for($i=0;$i<$num;$i++){
//           $insertInfo = $bi->filter('strip_tags')->addAll(array_slice($bookinfo,$i*500,500-$i));
//       }
            //分片插入

            $insertInfo = $bi->filter('strip_tags')->addAll($bookinfo);
          if($insertInfo){
          	$Model->commit();
          	unset($bookinfo);
          	//删除txt
            $msg = unlink($file_path)?'txt已删除':'txt删除失败';
            $this->success('添加书籍成功2：'.$msg);
          }else{
          	$Model->rollback();
                $msg = unlink($file_path)?'txt已删除':'txt删除失败';
                $this->error('添加书籍失败，请重试1'.$msg);
          }

} else {
    unlink($file_path);
    $this->error('添加书籍失败，请重试2');
}
}

public function checklogin() {
    if (empty($_SESSION['aid'])) {
        $this->redirect('Login/login');
    }
}

public function checkadmin() {
    $ad = M('admin');
    $admin = $ad->where(array('id' => $_SESSION['aid']))->find();
    return $admin;
}

public function checkwechat() {
    $wc = M('wechat');
    $wechat = $wc->where(array('aid' => $_SESSION['aid']))->find();
    return $wechat;
}

public function del_book() {
    $n = M('book');

    $bookinfo = "bookinfo";

//        $nn=M($bookinfo);

    $pic = $n->where(array('id' => $_GET['id']))->find();

//       unlink('Public/Uploads/book/' . $pic['img']);

    $i = $n->where(array('id' => $_GET['id']))->setField('del_time', time());
    if ($i > 0) {
     $ii = $nn->where(array('bid' => $_GET['id']))->delete();
     $this->success('删除成功', U('Book/book_list'));
 } else {
    $this->error('删除失败，请重试');
}
}

public function del_bookinfo() {

    $bookinfo = "bookinfo";
    $n = M($bookinfo);

    $i = $n->where(array('id' => $_GET['id']))->delete();
    if ($i > 0) {
        $this->success('删除成功!', U('Book/book_share?bid=' . $_GET['bid']));
    } else {
        $this->error('删除失败，请重试');
    }
}

public function delall_bookinfo() {

    $bookinfo = "bookinfo";
    $book = "book";
    $n = M($bookinfo);
    $b = M($book);
    $count = $n->where(array('bid' => $_GET['id']))->count();
    if($count>0){
      $i = $n->where(array('bid' => $_GET['id']))->delete();        	
  }
  
  $a = $b->where(array('id' => $_GET['id']))->delete();
  $this->success('删除成功!', U('Book/book_list')); 
  
}

public function comment() {
    $this->checklogin();
    $admin = $this->checkadmin();
    $this->assign('admin', $admin);
    $page = I('get.page', 1);
    $pre_page = I('get.pre_page', 10);

    $CommentModel = D('BookComment');
    $count = $CommentModel->count();
    $Page = new \Think\Page($count, $pre_page);
    $show = $Page->show();

    $comment = $CommentModel
    ->order('add_time desc')
    ->limit($Page->firstRow . ',' . $Page->listRows)
    ->select();
    $this->assign('page', $show);
    $this->assign('comment', $comment);
    $this->display();
}

    /*
     * $action  动作 add ,update, delete, select; update  
     * $model   对应模型   BookComment
     * $params  操作参数   comment_id:10|is_show:0
     * $url     跳转链接   Book|comment   控制器名|方法名
     */

    public function dowhat($action, $model, $params = '', $url = '') {
        $model = D($model);
        $params = explode('|', $params);
        $data = [];
        foreach ($params as $value) {
            $arr = explode(':', $value);
            $data[$arr[0]] = $arr[1];
        }
        if (!empty($url)) {
            $url = U(str_replace('|', '/', $url));
        } else {
            $url = $_SERVER['HTTP_REFERER'];
        }

        switch ($action) {
            case 'add':
            if ($model->add($data)) {
                redirect($url, 1, '成功');
            }
            break;
            case 'update':

            if ($model->save($data)) {
                redirect($url, 1, '成功');
            }

            break;
            case 'select':


            break;
            case 'delete':
            if ($model->where($data)->delete()) {
                redirect($url, 1, '成功');
            }

            break;

            default:
            redirect($url, 1, '失败');
            break;
        }
        redirect($url, 1, '失败');
    }

    public function changeNumber($bid) {
        $sql = "SET @num = 0;UPDATE n_bookinfo SET number = (@num := @num + 1) WHERE bid = {$bid}";
        $result = D('Bookinfo')->comment('修正章节序号')->execute($sql);
        
        //章节总字数
        
        $this->success('成功', U('Book/book_share', ['bid' => $bid]));
    }

    public function downbook() {
        $data = $this->params();
        if (checkDomain($data['url'])) {
            //链接
        } else {
            //连接测试服务器
            $Book = M('Book','n_','DB_CONFIG_DEV'); 
            $Bookinfo = M('Bookinfo','n_','DB_CONFIG_DEV'); 
            //书id
            $bid = $data['url'];
            $book = $Book->field('title,tid,img,author,content,sex,state,source')->find($bid);
            $book['count'] = $Bookinfo->where(['bid' => $bid])->count();
            echo json_encode($book);
        }
    }
    
    
    public function getContent() {
        header("Content-type: text/html; charset=gbk");
        $input = $this->params();
        $data = $input['data'];
        if(empty($data['url'])){
         $data['code'] = '10001'; 
         $data['message'] = 'url不能为空'; 
         $this->ajaxReturn($data);
     }
     $url = $data['url'];
     $html = http_curl($url,'get','html');
     $html = mb_convert_encoding($html, 'utf-8','GB2312');
     $title = '/<h1>(.*)<\/h1>/is';
     preg_match($title,$html,$matches);
     $matches = array_reverse($matches);
     $data['title'] = $matches['0'];
     $content = '/<div id="content" name="content">(.*)<\/p><\/div>/is';
     preg_match($content,$html,$matches);
 }
 
 public function article() {
    $params = $this->params();
    $input = $params['data'];
    if(!empty($input) && count($input)>0){
        $article = M('article');
        $bookinfo = D('Bookinfo')->field('bid')->find($input['biid']);
        $data['title'] = $input['title'];
        $data['description'] = $input['description'];
        $data['cover'] = $input['cover'];
        $data['bid'] = $bookinfo['bid'];
        $data['add_time'] = time();
        $id = $article->add($data,['bid'=>$data['bid']],true);
        if($id){
            $this->response(1,'保存成功',['id'=>$id]);
        }else{
            $this->response(2,'保存失败');
        }
    }
}

public function updateCountword() {
    $data = $this->params();
    $content = D('Bookinfo')->where(['bid'=>$data['id']])->getField('content',TRUE);
    $totalnum = 0;
    foreach ($content as  $value) {
        $totalnum += count_word($value);
    }
    $totalnum = round($totalnum/10000,0);
    $re = D('Book')->setField(['id'=>$data['id'],'totalwords'=>$totalnum]);
    $this->success('修改成功', U('Book/edit_book',['id'=>$data['id']]));
}


    public function allbuylog()
    {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        $page = I('get.page',1);
        $pre_page = I('get.pre_page',30);
        $b = M('bookshelves');
        $w = array();
        $w['n_bookshelves.is_all_buy'] = 1;
        if($_GET['user_id']){
            $w['n_bookshelves.user_id'] = $_GET['user_id'];
        }

        $count = $b->where($w)->count();
        $Page = new \Think\Page($count,$pre_page);
        $show = $Page->show();
        $field = '*,n_user.id As user_id,n_user.nickname,n_book.id as book_id,n_book.name as book_name';
        $logs = $b->where($w)->limit($Page->firstRow.','.$Page->listRows)->field($field)->order('n_bookshelves.add_time desc')->join(array('LEFT JOIN n_user ON n_user.id = n_bookshelves.user_id','LEFT JOIN n_book ON n_book.id = n_bookshelves.b_id'))->select();
        $this->assign('logs', $logs);
        $this->assign('page', $show);
        $this->display();
    }

    //购买一本书
    function delBuyBook(){

        if (empty($_GET['id'])) {
            $this->error('id不能为空');
        }
        $id = $_GET['id'];

        $bookshelves = D('bookshelves');
        $bookshelves->delete($id);
        $this->success("成功");
    }

    public  function add_book_chapter(){
        $this->checklogin();
        $this->display();
    }
}
